extends NodeState

@export var enemy: BasicEnemy

var velocity: Vector2 = Vector2.ZERO
var height: float = 0.0
var height_speed: float = 0.0

func _on_process(delta : float) -> void:
	enemy.position += velocity * delta
	process_air_time(delta)


func _on_enter() -> void:
	enemy.damageReceiver.set_deferred("monitorable", false)
	height = 0.0
	enemy.look_at_player()
	process_animation()
	process_affected()


func _on_exit() -> void:
	pass


func process_animation():
	enemy.animationPlayer.play(BasicEnemy.ANIMATION_FALL)


# 受到攻击时的效果
func process_affected():
	var emit_direction := enemy.take_damage_emit_direction()
	if emit_direction == null:
		return
	var direction: Vector2 = Vector2.RIGHT if emit_direction.x > 0 else Vector2.LEFT
	velocity = direction * enemy.knockback_intensity
	height_speed = enemy.knockdown_intensity


func process_air_time(delta: float):
	enemy.characterSprite.position = Vector2.UP * height

	height += height_speed * delta
	# 高度降为0时进入倒地状态
	if height < 0.0:
		height = 0.0
		velocity = Vector2.ZERO
		transition_state(BasicEnemy.STATE_GROUNDED)
	else:
		height_speed -= enemy.gravity * delta